<template>
	<view>
		<rock-shake title="摇一摇获得照片" @onrock="rockAndShake" @cancel="cancelMask" v-if="showMask"></rock-shake>

		<view class="page__hd">
			<view class="page__title">送出一封祝福锦囊</view>
			<view class="page__desc">带有<text style="color:red;">*</text>号的是必填项</view>
		</view>

		<view class="weui-cells__title">
			寄件人信息 ( <text class="address-ad-text" @tap="senderAutoLocate">点此快速输入</text> )
		</view>
		<locator ref="locator" :region="package.sender.region" @placeupdate="senderLocUpdate"></locator>

		<view class="weui-cells__title">收件人信息</view>
		<locator :auto="false" :region="package.target.region" :gps="package.target.gps" :customItem="'全部'" @placeupdate="targetLocUpdate"></locator>

		<view class="weui-cells__title">添加锦囊内容<text style="color:red;">*</text>（长按删除）</view>
		<view class="weui-cells weui-cells_after-title cps">
			<image-list :imgIds="package.imgList" :showDetail="showDetail" :detailIndex="detailIndex" :addBtn="true" @tapadd="onAdd"
			 @imglongpress="delImg"></image-list>
		</view>

		<!-- <view class="weui-cells__title">更多设置</view> -->
		<view class="weui-cells weui-cells_after-title">
			<view class="weui-cell weui-cell_switch">
				<view class="weui-cell__bd">自定义文本（需审核）</view>
				<view class="weui-cell__ft">
					<switch :checked="advancedMode" @change="advancedMode = !advancedMode" />
					<!-- <input class="weui-switch" type="checkbox"/>（需审核）（<text class="address-ad-text" @tap="showLogin=true">点此登录</text>） -->
				</view>
			</view>
		<!-- </view>
		
		<view class="weui-cells weui-cells_after-title"> -->
			<view class="weui-cell" v-if="advancedMode">
				<view class="weui-cell__hd">
					<view class="weui-label">寄件人</view>
				</view>
				<view class="weui-cell__bd">
					<input class="weui-input" placeholder="匿名" type="text" maxlength="16" v-model="package.sender.name"></input>
				</view>
			</view>
			<view class="weui-cell" v-if="advancedMode">
				<view class="weui-cell__hd">
					<view class="weui-label">收件人</view>
				</view>
				<view class="weui-cell__bd">
					<input class="weui-input" placeholder="所有人" type="text" maxlength="16" v-model="package.target.name"></input>
				</view>
			</view>
		</view>
		
		<view class="weui-cells__title" v-if="advancedMode">祝福语<text style="color:red;">*</text>（审核后可见）</view>
		<view class="weui-cells weui-cells_after-title" v-if="advancedMode">
			<view class="weui-cell">
				<view class="weui-cell__bd">
					<textarea class="weui-textarea" auto-height placeholder="写下你的祝福" v-model="package.content" maxlength="256"></textarea>
					<view class="weui-textarea-counter">{{package.content.length}}/256</view>
				</view>
			</view>
		</view>

		<!-- <view class="weui-cells__title" v-if="advancedMode">隐私设置<text style="color:red;">*</text>（该设置只针对祝福语及姓名，图片等其他内容是默认公开的）</view>
		<view class="weui-cells weui-cells_after-title" v-if="advancedMode">
			<radio-group @change="privateRadioChange">
				<label class="weui-cell weui-check__label" v-for="item in privateChoices" :key="item.value">
					<radio class="weui-check" :value="item.value" :checked="item.checked" />
					<view class="weui-cell__bd">{{item.name}}</view>
					<view class="weui-cell__ft weui-cell__ft_in-radio" v-if="item.checked">
						<icon class="weui-icon-radio" type="success_no_circle" size="16"></icon>
					</view>
				</label>
			</radio-group>
		</view> -->
		
		<view class="weui-cells weui-cells_after-title">
			<view class="weui-cell">
				<view class="weui-cell__bd">
					<button class="weui-btn" type="default" @tap="preview=true" style="color:black;" v-if="advancedMode">预览效果</button>
					<button class="weui-btn" type="primary" @tap='send'>寄出</button>
				</view>
			</view>
		</view>
		<!--  -->
		<package-detail :content="package" v-if="advancedMode && preview" :previewMode="true" @ontapcancel="preview=false"></package-detail>
	</view>
</template>

<script>
	import PackageDetail from '../../components/package-detail.vue'
	import RockShake from '../../components/rock-shake.vue'
	import Locator from '../../components/place-locator.vue'
	import ImageList from '../../components/image-list.vue'
	import utils from '../../common/function.js'
	import sys from '../../common/sys.js'
	import {
		CacheList
	} from '../../common/cache.js'
	import {
		Package, User, CrystalImage
	} from '../../common/service.js'
	const PKG = new Package()
	const IMG = new CrystalImage()
	const USER = new User()

	export default {
		components: {
			Locator,
			RockShake,
			ImageList,
			PackageDetail,
		},
		data() {
			return {
				package: {
					sender: {
						region: [],
						location: '',
						name: '',
						gps: null,
					},
					target: {
						region: ['中国', '湖北省', '武汉市', '全部'],
						location: '',
						name: '',
						gps: [114.291359, 30.430179], //武汉市位置
					},
					imgList: [],
					content: '',
					time: new Date(),
				},
				privateChoices: [{
						name: '所有人可见（需审核）',
						value: 'needaudit',
						checked: true
					},{
						name: '收件人手机号匹配可见',
						value: 'match'
					},{
						name: '默默祝福（仅我自己可见）',
						value: 'private'
					}
				],
				showMask: false,
				showDetail: false,
				detailIndex: 0,
				advancedMode: false,
				preview: false,
			}
		},
		onLoad: function(options) {
			uni.setNavigationBarTitle({
			    title: '邮寄 (Send)'
			});
			if (options.target) {
				let target = JSON.parse(decodeURIComponent(options.target))
				console.log(target)
				this.package.target = target
			}
		},
		onShow: function() {
			this.package.imgList = new CacheList('imgList').getList()
		},
		methods: {
			senderAutoLocate: function() {
				this.$refs.locator.autoLocate()
			},
			senderLocUpdate: function(loc) {
				if (loc.location) sys.toast_done('定位成功')
				this.package.sender = loc
			},
			targetLocUpdate: function(loc) {
				if (loc.location) sys.toast_done('定位成功')
				this.package.target = loc
			},
			onAdd: utils.freqAsync(1000, async function() {
				let choice = await sys.chooseFromMenu(['随机获取', '从收藏夹选择'])
				if (choice == '随机获取') {
					this.showMask = true
					this.rock = true
				} else if (choice == '从收藏夹选择') {
					sys.navigateTo('collection?selectionMode=1')
				} else; //user cancel, do nothing.
			}),

			delImg: async function(e) {
				if (await sys.modal('确认删除？', '')) {
					let imgs = new CacheList('imgList').filter((id, index) => !(id == e.imgId && index == e.index))
					this.package.imgList = imgs
				}
			},

			cancelMask: function() {
				// console.log('cancel rock')
				this.showMask = false
			},

			rockAndShake: utils.freqAsync(2000, async function(randNum) {
				// sys.toast_done('摇一摇成功')
				this.showMask = false
				let imageId = await this.getRandomImageId(randNum)
				this.package.imgList.push(imageId)
				this.detailIndex = this.package.imgList.length - 1
				// console.log(this.showDetail)
				this.showDetail = true
				new CacheList('imgList').push(imageId)
			}),

			getRandomImageId: async function(randNum) {
				let imgIdList = await IMG.getIdList()
				return imgIdList[(randNum * imgIdList.length)<<0]
				let imgs = new CacheSet('imgList')
				let imgid
				do {
					imgid = parseInt(Math.random() * 40)
					// console.log(imgid)
				} while (imgs.has(i))
				return imgid
			},
			// loginMeIn: function(){
				
			// },
			// privateRadioChange: function(e) {
			// 	this.package.status = e.detail.value
			// 	this.privateChoices = this.privateChoices.map(choice => {
			// 		choice.checked = (choice.value == e.detail.value)
			// 		return choice
			// 	})
			// },

			send: utils.freqAsync(1638, async function() {
				let p = this.package
				if (p.imgList.length == 0) return await sys.modal('需要添加内容', '至少需要添加一张图片作为内容')
				if (p.sender.region.length == 0) return await sys.modal('需要完善内容', '请选择您所在地区')
				let imgs = await IMG.getList(p.imgList)
				if (imgs.filter(img=>img.positive=="0").length>0){
					return await sys.modal('检测到负面内容', '请移除相应图片后再发送')
				}
				const self = this
				new TencentCaptcha('2034859887', async function(captcha) {
					if(captcha.ret==0){
						console.log(captcha)
						sys.toast_loading('投递中')
						await PKG.add(p, captcha)
						sys.toast_done('已寄出')
						sys.rm_cache('imgList')
						self.package.imgList=[]
						let pages = getCurrentPages()
						if (pages.length > 1) sys.navigateBack()
						else sys.redirectTo('/pages/pray/index')
					}
				}).show()
			}),
		}
	}
</script>

<style>
	@import "../../static/weui.min.css";

	.address-ad-text {
		text-decoration: underline;
		color: #33c;
	}
</style>
